package com.edu.modules.baseinfo.dao;

import com.edu.modules.baseinfo.model.StudentId;
import com.edu.modules.baseinfo.model.User;
import com.sari.common.persistence.BaseDao;
import com.sari.common.utils.DateUtils;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

/**
 * Created by lab on 2016/7/15.
 */
@Repository
public class AccountDao extends BaseDao {

	public User getUser(String userName, String userRole) {

		String sql = "";
		if(userRole.equals("0")){
			sql = "select a.user_id, a.user_name,a.pass_word from t_account a where a.user_role = ? and a.user_name = ?";
		}else if(userRole.equals("1")){
			sql = "select b.student_id AS user_id, b.student_name AS user_name,a.pass_word from t_account a,t_student b " +
					"where b.student_id = a.user_id and a.user_role = ? and a.user_name = ?";
		}else if(userRole.equals("2")){
			sql = "select b.teacher_id AS user_id, b.teacher_name AS user_name,a.pass_word from t_account a,t_teacher b " +
					"where b.teacher_id = a.user_id and a.user_role = ? and a.user_name = ?";
		}else{
			return null;
		}

		return (User) getJdbcTemplate().queryForObject(sql, new Object[]{userRole,userName},
			new RowMapper(){

				@Override
				public Object mapRow(ResultSet rs, int rowNum) {
					try {
						User user  = new User();
						user.setUserId(rs.getString("user_id"));
						user.setUserName(rs.getString("user_name"));
						user.setPassWord(rs.getString("pass_word"));
						return user;
					}catch (SQLException e){
						e.printStackTrace();
						return null;
					}
				}

		});
	}

	public Integer getAccountByName(String userName){

		String sql = "SELECT COUNT(*) FROM t_account WHERE user_name = ?";

		try {
			return getJdbcTemplate().queryForObject(sql,new Object[]{userName},Integer.class);
		}catch (EmptyResultDataAccessException e){
			return 0;
		}
	}

	public int addStudent(String studentId,String userName,String studentName,String openId,String createTime){

		String sql = "insert into t_student (student_id,phone,student_name,open_id,create_time) values(?,?,?,?,?)";

		return saveOrUpdateOrDelete(sql,studentId,userName,studentName,openId,createTime);
	}

	public Map getStudentId(String openId){

		String sql = "select student_id,student_name from t_student where open_id = ?";

		try {
			return super.getJdbcTemplate().queryForMap(sql,openId);
		}catch (EmptyResultDataAccessException e){
			return null;
		}
	}

	public int updatePwd(String userId,String passWord){

		String sql = "update t_account set pass_word = ?,update_time = ? where user_id = ?";

		return super.saveOrUpdateOrDelete(sql,passWord, DateUtils.getDateTime(),userId);
	}
}
